package com.bkfm.framework.core.rest;

import java.io.File;
import java.io.FileInputStream;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang3.StringUtils;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.poifs.filesystem.POIFSFileSystem;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.multipart.commons.CommonsMultipartResolver;
import org.yak.core.nosql.MongoDBConfig;
import org.yak.core.provider.SqlProvider;
import org.yak.core.utils.ConfigUtils;
import org.yak.core.utils.DateUtil;
import org.yak.core.web.BaseRest;
import org.yak.core.web.Result;
import org.yak.core.web.ResultSet;
import org.yak.core.web.Result.Status;
import org.yak.common.digest.DESUtils;
import org.yak.common.file.FileToZip;
import org.yak.common.file.FileUtil;
import org.yak.common.utils.RandomUtil;

import com.bkfm.framework.core.api.service.IBkfmTableMetaServer;
import com.bkfm.framework.core.entity.BkfmFiles;
import com.bkfm.framework.core.entity.BkfmFilter;
import com.bkfm.framework.core.entity.BkfmTableMetaData;
import com.bkfm.framework.utils.BkfmExpImpColumn;

/**
 * 工具接口
 * @author Administrator
 *
 */
@RestController
@RequestMapping("/bkfm/common/v1/**")
public class BkfmUtilRest extends BaseRest<BkfmTableMetaData>{

	@Resource
	private IBkfmTableMetaServer tableMetaService;
	
	/**
	 * 附件上传
	 * @param req
	 * @return
	 */
	@RequestMapping("/upload")
	public Result uploadFile(HttpServletRequest req) {
		try {
			List<BkfmFiles> bkfmFilesList = new ArrayList<BkfmFiles>();
			CommonsMultipartResolver cmr = new CommonsMultipartResolver(req.getSession().getServletContext());
			if (cmr.isMultipart(req)) {
				MultipartHttpServletRequest mRequest = (MultipartHttpServletRequest)req;
				Iterator<String> files = mRequest.getFileNames();
				while (files.hasNext()) {
					BkfmFiles bkmfFiles = new BkfmFiles();
	                MultipartFile mFile = mRequest.getFile(files.next());
	                String fileExt = FileUtil.getFileExt(mFile.getOriginalFilename()).toLowerCase();
                	String fileId = RandomUtil.getRandom();
                    String fileName = fileId+"."+ fileExt;
                    //当前年月日的文件夹
                    String nowDate = DateUtil.nowDate();
                    String path = ConfigUtils.getFileUploadDir() +"/"+nowDate + "/" + fileName;
                    File localFile = new File(path);
                    if(!localFile.getParentFile().exists()){
                    	localFile.getParentFile().mkdirs();
                    }
                    mFile.transferTo(localFile);
                    
                    //获取文件名
                    bkmfFiles.setFile_id(fileId);
                    bkmfFiles.setFile_name(mFile.getOriginalFilename());
                    bkmfFiles.setFile_ext(fileExt);
                    bkmfFiles.setFile_len(mFile.getSize());
                    bkmfFiles.setFile_size(FileUtil.getNetFileSizeDescription(mFile.getSize()));
                    bkmfFiles.setFile_path(path);
                	
                	bkfmFilesList.add(bkmfFiles);
				}
				
				tableMetaService.uploadFile(bkfmFilesList);
			}
			
			return new Result(Status.OK,bkfmFilesList);
		}catch(Exception e) {
			logger.error("上传文件异常",e);
			return new Result(Status.ERROR,e.getMessage());
		}
	}
	/**
	 * 导出Excel
	 * @param bkfmFilter
	 * @param expColumn
	 * @return
	 */
	@RequestMapping("/export")
	public Result exportExcel(BkfmFilter bkfmFilter,String expColumn) {
		try {
			String file_path = tableMetaService.exportData(bkfmFilter, Arrays.asList(StringUtils.split(expColumn,",")));
			return new Result(Status.OK,"success",file_path);
		}catch(Exception e) {
			logger.error("导入文件异常",e);
			return new Result(Status.ERROR,e.getMessage());
		}
	}
	
	/**
	 * 上传导入Excel文件
	 * @param req
	 * @param bkfmFilter
	 * @return
	 */
	@RequestMapping("/loadimpexcelcol")
	public Map<String,Object> loadImpExcelColumn(HttpServletRequest req,BkfmFilter bkfmFilter) {
		Map<String,Object> mapResult = new HashMap<String,Object>();
		mapResult.put("success", false);
		try {
			Result rs = uploadFile(req);
			if(rs.getStatus()==Status.OK) {
				List<?> bkfmFilesList = rs.getList();
				if(bkfmFilesList !=null && !bkfmFilesList.isEmpty()) {
					BkfmFiles bkfmFile = (BkfmFiles)bkfmFilesList.get(0);
					File impFile = new File(bkfmFile.getFile_path());
					//读取excel表头
					POIFSFileSystem fs = new POIFSFileSystem(new FileInputStream(impFile));
			        //读取excel模板
					HSSFWorkbook wb = new HSSFWorkbook(fs);
			        //读取了模板内所有sheet内容
			        HSSFSheet sheet = wb.getSheetAt(0);
			        HSSFRow xssfRow = sheet.getRow(0);
			        int count = xssfRow.getLastCellNum();
			        wb.close();
			        Map<String,Object> queryFilter = new HashMap<String,Object>();
					queryFilter.put("obj_path", bkfmFilter.getObj_path());
					List<Map<String,Object>> fields = MongoDBConfig.queryMapList(SqlProvider.MONGODB_NAME, SqlProvider.MONGODB_TABLEMETADATA_NAME, queryFilter);
					if(fields == null || fields.isEmpty()) {
						mapResult.put("result", new Result(Status.ERROR,"没有查询到业务模型字段信息"));
						return mapResult;
					}
					Map<String,Object> param = fields.get(0);
					queryFilter.clear();
					queryFilter.put("father_tablemetadata_id", param.get("TABLEMETADATA_ID"));
					fields = MongoDBConfig.queryMapList(SqlProvider.MONGODB_NAME, SqlProvider.MONGODB_TABLEMETADATA_NAME, queryFilter);
					if(fields == null || fields.isEmpty()) {
						mapResult.put("result", new Result(Status.ERROR,"没有查询到业务模型字段信息"));
						return mapResult;
					}
					List<Map<String,Object>> valuelist = new ArrayList<Map<String,Object>>();
					for(Map<String,Object> fieldMap : fields) {
						Map<String,Object> field = new HashMap<String,Object>();
						String columnName = String.valueOf(fieldMap.get("ZH_CN"));
						field.put("field_label", fieldMap.get("ZH_CN"));
						field.put("field_name", fieldMap.get("EN_US"));
				        for(int i=0;i<count;i++) {
				        	//excel表头列
				        	String excel_column_head = xssfRow.getCell(i).getStringCellValue();
				        	if(columnName.equals(excel_column_head)) {
				        		field.put("field_excel_head", columnName);
				        		field.put("field_excel_head_col", i);
				        		break;
				        	}
				        }
				        valuelist.add(field);
					}

					
					session.setAttribute(bkfmFile.getFile_id(), impFile);
					Map<String,Object> resultMap = new HashMap<String,Object>();
					resultMap.put("file_id", bkfmFile.getFile_id());
					resultMap.put("imp_field", valuelist);
					mapResult.put("success", true);
					mapResult.put("result", new Result(Status.OK,"success",resultMap));
					
					return mapResult;
				}
				mapResult.put("result", new Result(Status.ERROR,"加载Excel文件表头失败"));
				return mapResult;
			}else {
				return mapResult;
			}
		}catch(Exception e) {
			logger.error("导入文件异常",e);
			mapResult.put("result", new Result(Status.ERROR,e.getMessage()));
		}
		return mapResult;
	}
	
	/**
	 * 导入excel数据
	 * @param req
	 * @param file_id
	 * @param bkfmFilter
	 * @param param
	 * @return
	 */
	@RequestMapping("/import")
	public Result importExcel(String file_id,BkfmFilter bkfmFilter,@RequestBody List<BkfmExpImpColumn> imp_field_list) {
		try {
			File bkfmFile = (File)session.getAttribute(file_id);
			logger.info(bkfmFilter.getObj_path());
			if(bkfmFile==null) {
				return new Result(Status.ERROR,"文件不存在或者文件已导入");
			}
			tableMetaService.importData(bkfmFilter, imp_field_list, bkfmFile);
			bkfmFile.delete();
			session.removeAttribute(file_id);
			return new Result(Status.OK,"success");
		}catch(Exception e) {
			logger.error("导入文件异常",e);
			return new Result(Status.ERROR,e.getMessage());
		}
	}
	
	/**
	 * 根据附件id下载附件
	 * @param file_id
	 * @param response
	 * @param model
	 */
	@RequestMapping("/downloadfile")
	public Result downloadfile(String file_id,HttpServletResponse response,Model model){
		try {
			BkfmFilter bkfmFilter = new BkfmFilter();
			bkfmFilter.setObj_path("ROOT/XTGLPT/JCSJGL/WJGL/BLK_FILES");
			bkfmFilter.setFilter(" FILE_ID = '"+file_id+"'");
			ResultSet result = tableMetaService.queryTableModelMetaResultSet(bkfmFilter);
			if(result == null || result.isEmpty()) {
				logger.error("通过附件id查询附件存在");
				return new Result(Status.ERROR,"通过附件id查询附件存在");
			}
			String filePath = String.valueOf(result.get("FILE_PATH"));
	        
	        return new Result(Status.OK,"success",DESUtils.encryption(filePath, DESUtils.SECRETKEY));
		}catch(Exception e) {
			logger.error("下载文件异常",e);
			return new Result(Status.ERROR,e.getMessage());
		}
	}
	
	/**
	 * 打包下载附件
	 * @param fileid_list
	 * @param response
	 * @param model
	 */
	@RequestMapping("/downloadfilezip")
	public Result downloadfileZip(@RequestBody List<String> fileid_list,HttpServletResponse response,Model model){
		try {
			if(fileid_list ==null || fileid_list.isEmpty()) {
				logger.error("下载文件失败，无效的附件编码");
				return new Result(Status.ERROR,"下载文件失败，无效的附件编码");
			}
			BkfmFilter bkfmFilter = new BkfmFilter();
			bkfmFilter.setObj_path("ROOT/XTGLPT/JCSJGL/WJGL/BLK_FILES");
			bkfmFilter.setFilter(" FILE_ID IN (");
			int count=0;
			for(String file_id : fileid_list) {
				if(count == 0) {
					bkfmFilter.setFilter(bkfmFilter.getFilter()+"'"+file_id+"'");
				}else {
					bkfmFilter.setFilter(bkfmFilter.getFilter()+",'"+file_id+"'");
				}
				count++;
			}
			bkfmFilter.setFilter(bkfmFilter.getFilter()+")");
			List<ResultSet> resultlist = tableMetaService.queryTableModelMetaResultSetList(bkfmFilter);
			List<String> fileList = new ArrayList<String>();
			for(ResultSet result : resultlist) {
				String filePath = String.valueOf(result.get("FILE_PATH"));
		        // 读到流中
				File file = new File(filePath);
				if(!file.exists()) {
					logger.error("附件："+result.get("FILE_NAME")+",不存在");
					continue;
				}
				fileList.add(filePath);
			}
			if(fileList.isEmpty()) {
				logger.error("无效的文件列表");
				return new Result(Status.ERROR,"无效的文件列表");
			}
			String nowDate = DateUtil.nowDate();
        	String fileId = RandomUtil.getRandom();
            String fileName = fileId+".zip";
            String zipFile = ConfigUtils.getFileExportDir()+"/"+nowDate + "/" + fileName;
            File localFile = new File(zipFile);
            if(!localFile.getParentFile().exists()){
            	localFile.getParentFile().mkdirs();
            }
			FileToZip.fileToZip(fileList, zipFile);
			
			return new Result(Status.OK,"success",DESUtils.encryption(zipFile, DESUtils.SECRETKEY));
		}catch(Exception e) {
			logger.error("打包下载附件异常",e);
			return new Result(Status.ERROR,e.getMessage());
		}
	}
}
